import random
from io import BytesIO
import base64
import gvcode

def get_code(n=6,alpha=True):
    s = '' # 创建字符串变量,存储生成的验证码
    for i in range(n):  # 通过for循环控制验证码位数
        num = random.randint(0,9)  # 生成随机数字0-9
        if alpha: # 需要字母验证码,不用传参,如果不需要字母的,关键字alpha=False
            upper_alpha = chr(random.randint(65,90))
            lower_alpha = chr(random.randint(97,122))
            num = random.choice([num,upper_alpha,lower_alpha])
        s = s + str(num)
    return s

def gen_base64_verify_code_img(size=(120,30),length=6):
    """
    生成base64格式的验证码图片
    @param size: 图片的大小，格式（宽，高），默认为(120, 30)
    @param length: 验证码字符个数
    @return: [0]:  base64编码的字符串
    @return: [1]: 验证码图片中的字符串
    """
    im, vcode = gvcode.generate(size=size,length=length)
    out = BytesIO()
    im.save(out, format='PNG')
    return str(base64.b64encode(out.getvalue()),encoding='utf8'), vcode

def send_code_by_aliyun(phone):
    """向指定的手机号发送验证码短信"""
    pass



if __name__ == '__main__':
    code = get_code(alpha=False)
    print(gen_base64_verify_code_img())
